//
//  WBNewFeatureView.swift
//  weibo
//
//  Created by iobit on 2017/07/04.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    
    @IBOutlet weak var scorllView: UIScrollView!
    
    @IBOutlet weak var enterButton: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBAction func enterStatus(_ sender: UIButton) {
        removeFromSuperview()
    }
    
    class func newFeatureView()->WBNewFeatureView {
        
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        // 从XIB加载的视图，默认是600*600
        v.frame = UIScreen.main.bounds
        return v
    }
    
    override func awakeFromNib() {
        // 添加四个图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let imageView = UIImageView(image: UIImage(named: imageName))
            imageView.frame = rect.offsetBy(dx: CGFloat(i)*rect.width, dy: 0)
            scorllView.addSubview(imageView)
        }
        // 设置scrollView属性
        scorllView.contentSize = CGSize(width: rect.width*CGFloat(count+1), height: rect.height)
        
        scorllView.bounces = false  //不允许上下左右边界页面的拖动翻页
        scorllView.isPagingEnabled = true //允许拖动翻页不过半时自动回弹
        scorllView.showsVerticalScrollIndicator = false //垂直滑动栏
        scorllView.showsHorizontalScrollIndicator = false  //水平滑动栏
        
        scorllView.delegate = self
        
        // 隐藏按钮
        enterButton.isHidden = true
    }
}

extension WBNewFeatureView: UIScrollViewDelegate {

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 滚动到最后一屏，让视图删除
        let page = Int(scrollView.contentOffset.x/scrollView.bounds.width)
        
        // 如果滚动到最后一页，删除视图
        if page==scrollView.subviews.count {
            removeFromSuperview()
        }
        //倒数第二页显示按钮
        enterButton.isHidden = (page != scrollView.subviews.count-1)
        
    }
    
    // 滚动时会调用此方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 一旦滚动，则隐藏按钮
        enterButton.isHidden = true
        
        // 加0.5，使滑动超过一半时，pageControl即变为下一页的点；若不加则会等到下一页全部展示之后才会变为下一个点
        let page = Int(scorllView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
        
    }
    
}


